export const formatTime = function (time, fmt) {
  const date = new Date(time);
  var o = {
    'M+': date.getMonth() + 1, //月份
    'd+': date.getDate(), //日
    'H+': date.getHours(), //小时
    'm+': date.getMinutes(), //分
    's+': date.getSeconds(), //秒
    'q+': Math.floor((date.getMonth() + 3) / 3), //季度
    S: date.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + '').substr(4 - RegExp.$1.length)
    );
  for (var k in o)
    if (new RegExp('(' + k + ')').test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
      );
  return fmt;
};

export const formatTimeFlex = function (timestamp, mode = 0) {
  var curTimestamp = parseInt(new Date().getTime()); //当前时间戳
  var timestampDiff = curTimestamp - timestamp; // 参数时间戳与当前时间戳相差秒数
  var curDate = new Date(curTimestamp); // 当前时间日期对象
  var tmDate = new Date(timestamp); // 参数时间戳转换成的日期对象

  var Y = tmDate.getFullYear(),
    m = tmDate.getMonth() + 1,
    d = tmDate.getDate();
  // console.log("--- 年月日----->", timestampDiff);
  if (mode === 0) {
    if (timestampDiff < 60 * 1000) {
      // 一分钟以内
      return '刚刚';
    } else if (
      curDate.getFullYear() == Y &&
      curDate.getMonth() + 1 == m &&
      curDate.getDate() == d
    ) {
      if (timestampDiff < 1 * 60 * 60 * 1000) {
        //一小时内
        var timeString = parseInt(timestampDiff / 1000 / 60);
        return timeString + '分钟前';
      } else if (
        timestampDiff > 1 * 60 * 60 * 1000 &&
        timestampDiff < 2 * 60 * 60 * 1000
      ) {
        return '1小时前';
      } else {
        // 同一天
        return formatTime(timestamp, 'HH:mm');
      }
    } else if (curDate.getFullYear() == Y) {
      // 同一年
      return formatTime(timestamp, 'MM-dd');
    } else {
      return formatTime(timestamp, 'yyyy-MM-dd');
    }
  } else if (mode === 1) {
    if (
      curDate.getFullYear() == Y &&
      curDate.getMonth() + 1 == m &&
      curDate.getDate() == d
    ) {
      // 同一天
      return formatTime(timestamp, 'HH:mm');
    } else if (curDate.getFullYear() == Y) {
      // 同一年
      return formatTime(timestamp, 'MM-dd HH:mm');
    } else {
      return formatTime(timestamp, 'yyyy-MM-dd HH:mm');
    }
  }
};

// 校验手机号格式是否正确（兼容国内国际号码）
export const checkPhoneValid = (number) => {
  // 兼容国内/国际手机号
  // 参见 https://cloud.tencent.com/developer/article/1140913
  const phones = {
    'ar-DZ': /^(\+?213|0)(5|6|7)\d{8}$/,
    'ar-SY': /^(!?(\+?963)|0)?9\d{8}$/,
    'ar-SA': /^(!?(\+?966)|0)?5\d{8}$/,
    'en-US': /^(\+?1)?[2-9]\d{2}[2-9](?!11)\d{6}$/,
    'cs-CZ': /^(\+?420)? ?[1-9][0-9]{2} ?[0-9]{3} ?[0-9]{3}$/,
    'de-DE':
      /^(\+?49[ \.\-])?([\(]{1}[0-9]{1,6}[\)])?([0-9 \.\-\/]{3,20})((x|ext|extension)[ ]?[0-9]{1,4})?$/,
    'da-DK': /^(\+?45)?(\d{8})$/,
    'el-GR': /^(\+?30)?(69\d{8})$/,
    'en-AU': /^(\+?61|0)4\d{8}$/,
    'en-GB': /^(\+?44|0)7\d{9}$/,
    'en-HK': /^(\+?852\-?)?[569]\d{3}\-?\d{4}$/,
    'en-IN': /^(\+?91|0)?[789]\d{9}$/,
    'en-NZ': /^(\+?64|0)2\d{7,9}$/,
    'en-ZA': /^(\+?27|0)\d{9}$/,
    'en-ZM': /^(\+?26)?09[567]\d{7}$/,
    'es-ES': /^(\+?34)?(6\d{1}|7[1234])\d{7}$/,
    'fi-FI': /^(\+?358|0)\s?(4(0|1|2|4|5)?|50)\s?(\d\s?){4,8}\d$/,
    'fr-FR': /^(\+?33|0)[67]\d{8}$/,
    'he-IL': /^(\+972|0)([23489]|5[0248]|77)[1-9]\d{6}/,
    'hu-HU': /^(\+?36)(20|30|70)\d{7}$/,
    'it-IT': /^(\+?39)?\s?3\d{2} ?\d{6,7}$/,
    'ja-JP': /^(\+?81|0)\d{1,4}[ \-]?\d{1,4}[ \-]?\d{4}$/,
    'ms-MY':
      /^(\+?6?01){1}(([145]{1}(\-|\s)?\d{7,8})|([236789]{1}(\s|\-)?\d{7}))$/,
    'nb-NO': /^(\+?47)?[49]\d{7}$/,
    'nl-BE': /^(\+?32|0)4?\d{8}$/,
    'nn-NO': /^(\+?47)?[49]\d{7}$/,
    'pl-PL': /^(\+?48)? ?[5-8]\d ?\d{3} ?\d{2} ?\d{2}$/,
    'pt-BR': /^(\+?55|0)\-?[1-9]{2}\-?[2-9]{1}\d{3,4}\-?\d{4}$/,
    'pt-PT': /^(\+?351)?9[1236]\d{7}$/,
    'ru-RU': /^(\+?7|8)?9\d{9}$/,
    'sr-RS': /^(\+3816|06)[- \d]{5,9}$/,
    'tr-TR': /^(\+?90|0)?5\d{9}$/,
    'vi-VN':
      /^(\+?84|0)?((1(2([0-9])|6([2-9])|88|99))|(9((?!5)[0-9])))([0-9]{7})$/,
    'zh-CN': /^(\+?0?86\-?)?1[3456789]\d{9}$/,
    'zh-TW': /^(\+?886\-?|0)?9\d{8}$/
  };
  const regArr = Object.values(phones);
  return regArr.some((reg) => reg.test(number));
};

// 校验邮箱格式是否正确
export const checkEmailValid = (email) => {
  const reg =
    /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-_.])+[A-Za-z\d]{2,5}$/;
  return reg.test(email);
};

// 计算两个时间相隔天数
export const getDaysBetween = (dateString1, dateString2) => {
  let startDate = Date.parse(dateString1);
  let endDate = Date.parse(dateString2);
  if (startDate > endDate) {
    return 0;
  }
  if (startDate == endDate) {
    return 1;
  }
  let days = (endDate - startDate) / (1 * 24 * 60 * 60 * 1000);
  return days;
};

export const formatHtml = (str) => {
  return str
    ? str
        .replace(/↵/gi, ' <br />')
        .replace(/(\n)/gi, ' <br />')
        .replace(/(\\n)/gi, ' <br />')
        .replace(/>( )*<br \/>( )*</gi, '><')
        .replace(/<img/gi, '<img class="inner-img"')
        .replace(/<p/gi, '<p class="inner-p"')
        .replace(/<span/gi, '<img class="inner-span"')
        .replace(/<table/gi, '<img class="inner-table"')
    : '';
};


// 获取字符长度（汉字视为两个字符，英文为一个字符）
export const getByteLength = (str) => {
  str = str ? str : '';
  var len = 0;
  for (var i = 0; i < str.length; i++) {
    if (str.charCodeAt(i) > 127) {
      len += 2;
    } else {
      len++;
    }
  }
  return len;
};

// 检测密码强度（字母、数字、特殊符号组成的8-20位字符）
export const checkPassword = (str) => {
  // var reg = /^(?=.*[a-zA-Z])(?=.*\d)[^]{6,20}$/;
  var reg =
    /^(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[._~!@#$^&*])[A-Za-z0-9._~!@#$^&*]{8,20}$/;

  if (reg.test(str)) return true;
  return false;
};

// 获取url中的信息
export const getUrlObj = (url) => {
  var hostname = '';
  var port = '';
  var urls = url.split('/');
  var domain = urls[2];
  var protocol = urls[0];
  if (domain) {
    var domainList = domain.split(':');
    hostname = domainList[0];
    if (domainList.length > 1) {
      port = domainList[1];
    }
  }
  return { hostname, port, protocol };
};

// px 转换为 rpx ，传参类型是数字（Number）
export const pxToRpx = (px) => {
  let deviceWidth = uni.getSystemInfoSync().windowWidth;
  let rpx = (750 / deviceWidth) * Number(px);
  return Math.floor(rpx);
};

// 防抖
export const debounce = (fn, delay) => {
  var timeout = null;
  return function () {
    var that = this;
    clearTimeout(timeout);
    timeout = setTimeout(function () {
      fn.apply(that, arguments);
    }, delay);
  };
};
// 富文本内容格式化(img处理)
export const formatRichText = (html) => {
  // console.log("formatRichText", html);

  if (!html) return;
  let adjustedHtml = html
    .replace(/<img[^>]*>/gi, function (match, capture) {
      // 查找所有的 img 元素
      return match.replace(/style=".*"/gi, '').replace(/style='.*'/gi, ''); // 删除找到的所有 img 元素中的 style 属性
    })
    .replace(/\<img/gi, '<img style="width:100%;"') // 对 img 元素增加 style 属性，并设置宽度为 100%
    .replace(/var\(\s*--[^;\)]+\s*\)/g, '')
    .replace(/\*/g, '');
  // .replace(/font-family\s*:\s*[^;]+;/g, "");
  if (adjustedHtml.length > 15000) {
    //为了防止误伤，富文本很长的时候才删除div和div的样式，因为一般很长的都是直接复制别的网站的内容的，目前是为了处理id=6161690599420750的职讯里文字不显示的问题
    adjustedHtml = adjustedHtml.replace(
      /<div[^>]*style="[^"]*"[^>]*>/g,
      '<div>'
    );
  }
  // console.log("formatRichText After", adjustedHtml);
  return adjustedHtml;
};
// 自定义延时吐司提示
export const showDelayToastTip = (msg, delayTime) => {
  if (delayTime > 0) {
    return setTimeout(() => {
      uni.showToast({
        title: msg,
        icon: 'none',
        duration: 1500
      });
    }, delayTime);
  } else {
    uni.showToast({
      title: msg,
      icon: 'none',
      duration: 1500
    });
  }
};

// 根据类型 ，获取神兽封面图片 type-神兽类型
export const getDivineBeastCover = (type) => {
  if (type == 'ESFP') {
    //毕方
    return 'https://img3.job1001.com/ypMp/elan/images/career/careerAssessResult/毕方_01.png';
  } else if (type == 'ESTJ') {
    // 驳
    return 'https://img3.job1001.com/ypMp/elan/images/career/careerAssessResult/驳_01.png?v=1';
  } else if (type == 'ESFJ') {
    // 英招
    return 'https://img3.job1001.com/ypMp/elan/images/career/careerAssessResult/英招_01.png';
  } else if (type == 'ESTP') {
    // 饕餮
    return 'https://img3.job1001.com/ypMp/elan/images/career/careerAssessResult/饕餮_01.png';
  } else if (type == 'ISTJ') {
    // 乘黄
    return 'https://img3.job1001.com/ypMp/elan/images/career/careerAssessResult/乘黄_01.png';
  } else if (type == 'ISFJ') {
    // 孰湖
    return 'https://img3.job1001.com/ypMp/elan/images/career/careerAssessResult/孰湖_01.png';
  } else if (type == 'ISTP') {
    // 天狗
    return 'https://img3.job1001.com/ypMp/elan/images/career/careerAssessResult/天狗_01.png';
  } else if (type == 'ISFP') {
    // 九尾狐
    return 'https://img3.job1001.com/ypMp/elan/images/career/careerAssessResult/九尾狐_01.png';
  } else if (type == 'INTP') {
    // 鲲鹏
    return 'https://img3.job1001.com/ypMp/elan/images/career/careerAssessResult/鲲鹏_01.png';
  } else if (type == 'ENTP') {
    // 獬豸（xiè zhì）
    return 'https://img3.job1001.com/ypMp/elan/images/career/careerAssessResult/獬豸_01.png';
  } else if (type == 'ENFP') {
    // 凤凰
    return 'https://img3.job1001.com/ypMp/elan/images/career/careerAssessResult/凤凰_01.png';
  } else if (type == 'ENFJ') {
    // 金蟾
    return 'https://img3.job1001.com/ypMp/elan/images/career/careerAssessResult/金蟾_01.png';
  } else if (type == 'INFP') {
    // 鲛人
    return 'https://img3.job1001.com/ypMp/elan/images/career/careerAssessResult/鲛人_01.png';
  } else if (type == 'INTJ') {
    // 白泽
    return 'https://img3.job1001.com/ypMp/elan/images/career/careerAssessResult/白泽_01.png';
  } else if (type == 'INFJ') {
    // 夫诸
    return 'https://img3.job1001.com/ypMp/elan/images/career/careerAssessResult/夫诸_01.png';
  } else if (type == 'ENTJ') {
    // 青龙
    return 'https://img3.job1001.com/ypMp/elan/images/career/careerAssessResult/青龙_01.png';
  }

  return 'https://img3.job1001.com/ypMp/elan/images/career/careerAssessResult/青龙_01.png';
};

// 解析生成二维码的参数scene
export const extractParams = (scene) => {
  const params = {};
  const paramArray = scene.split('&');

  for (let i = 0; i < paramArray.length; i++) {
    const keyValue = paramArray[i].split('=');
    params[keyValue[0]] = keyValue[1];
  }

  return params;
};

export function insertDefault(region) {
  return region.map((ele)=>{
      if (ele.children) {
          ele.children.unshift({
              value: ele.value,
              label: "不限"
          });
          insertDefault(ele.children)
      }
      return ele
  }
  )
}

// url转换http为https
export function httpToHttps(url) {
  if (!url) return '';
  if (url.startsWith('//')) {
    return 'https:' + url;
  }
  return url.replace(/^http:/, 'https:');
}